$(function () {
    // 得到所有的菜品分类
    $.ajax({
        type: "get",
        url: "http://192.168.1.30:8080/dishCategory/all",
        // 将页面输入的值变成json格式
        dataType: "json",
        success: function (msg) {
            console.log(msg);
                $.each(msg.date.list, function (i, n) {
                    // 把数据库结果集的值绑定到页面上
                    var op = $("<option class='categoryOp' value=" + n.id + ">" + n.dishCategoryName + "</option>");
                    $("#dishCategory").append(op);
                })
             // 从url地址上获取参数
            var url = window.location.href;
            // 获取url地址上面的参数  id  key=value  截取=号后面的值
            var id = url.substr(url.lastIndexOf("=") + 1);
            //    根据菜品id得到指定的菜品信息
            $.ajax({
                type: "get",
                url: "http://192.168.1.30:8080/dish/findOne/" + id,
                success: function (msg) {
                   console.log(msg);
                    var dish = msg.date.dish;
                    $("#dish_name").val(dish.dishName);
                    $("#price").val(dish.price);
                    // selecte默认选中的option
                    $("#dishCategory").find("option[value='" + dish.category.id + "']").attr('selected', true);
                //    根据id获取菜品对象  但是页面默认隐藏
                    $("#dishId").val(dish.id);
                }
            });
        }
    });
    // 点击保存修改成功
    $("#updateDish").click(function () {
        var dish_name = $("#dish_name").val();
        var price = $("#price").val();
        var dishCategory = $("#dishCategory").find("option:selected").attr("value");
        var id = $("#dishId").val();
        if (dish_name == "") {
            alert("菜品名称不能为空");
            return;
        }
        if (dishCategory == 0) {
            alert("菜品分类未选择");
            return;
        }
        if (price == "") {
            alert("菜品价格不能为空");
            return;
        }
        var json = {
            "id":id,
            "dishName": dish_name,
            "price": price,
            "picPath":"http://192.168.1.30:8080/Desert.jpg",
            "category": {
                "id": dishCategory
            }
        }
        // 修改菜品对象
        $.ajax({
            type: "post",
            url: "http://192.168.1.30:8080/dish/update",
            dataType:"json",
            data: JSON.stringify(json),
            contentType:"application/json;charset=UTF-8",
            success: function (msg) {
                if (msg.code == 200) {
                    alert("修改菜品成功");
                } else {
                    alert("修改菜品失败");
                }

                window.location.href = "../tt/showDishes.html";
            }
        });
    })
})